#include "widget.h"
#include "ui_widget.h"
#include <QThread>
#include <QDebug>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //禁止编辑
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->pushButton_stop->setEnabled(false);

    timer = new QTimer(this);
    //动态分配空间，不能指定父对象
    mythread = new My_Thread;
    //创建子线程
    thread = new QThread(this);
    //把自定义的线程加入到子线程中
    mythread->moveToThread(thread);

    //处理子线程发送的信号
    connect(mythread, &My_Thread::mySignal, this, &Widget::dealsignal);
    qDebug() << "主线程号：" << QThread::currentThread();
    //发送信号给子线程，通过信号和槽调用子线程的线程处理函数
    connect(this, &Widget::startThreadSignal, mythread, &My_Thread::myTimerout);
    //关闭主窗口
    connect(this, &Widget::destroyed, this, &Widget::dealclose);

}
void Widget::numcheck(int cnum, int max, int *buf)
{
    while(buf[cnum] == buf[cnum-1])
    {
        buf[cnum] = rand()%max + 1;
    }
}



Widget::~Widget()
{
    delete ui;
}


void Widget::dealsignal()
{
    qsrand(time(NULL));
    int i=0;
       //产生5以内的随机数
      int ss[6]={0};
    for (;i<6;i++) {
        ss[i]=qrand()%33+1;
        if(0!=i)
        {
         numcheck(i,33,ss);


        }

    }

    for (i=0;i<6;i++) {
        //qDebug()<<"红球》》"<<ss[i];
        QTableWidgetItem *item = new QTableWidgetItem;

                       item->setText(QString::number(ss[i]));

                       item->setFont(QFont("song", 34));
                       item->setForeground(QBrush(QColor(255,0,0)));

                       ui->tableWidget->setItem(0,i,item);

    }

    QTableWidgetItem *item = new QTableWidgetItem;

                   item->setText(QString::number(qrand()%16+1));

                   item->setFont(QFont("song", 34));
                   item->setForeground(QBrush(QColor(0,0,255)));

                   ui->tableWidget->setItem(0,6,item);
                  // update();
     ms++;
     if (ms==60)
     {
         ms=0;
         ms++;

     }
     //设定lcd的值
     ui->lcdNumber_1->display(ms);
}

void Widget::dealclose()
{
    mythread->setFlag(true);
    thread->quit();
    thread->wait();
    delete mythread;
}

void Widget::on_pushButton_start_clicked()
{
    if (thread->isRunning() == true) {
        return;
    }
    ui->pushButton_stop->setEnabled(true);
    ui->pushButton_start->setEnabled(false);
    //启动线程，但是没有启动线程处理函数
    thread->start();
    mythread->setFlag(false);
    //不能直接调用线程处理函数
    //直接调用导致线程处理函数和主线程在同一个线程
    //只能通过信号和槽调用
    emit startThreadSignal();
}

void Widget::on_pushButton_stop_clicked()
{
    ms=0;
    if (thread->isRunning() == false) {
        return;
    }
    mythread->setFlag(true);
    thread->quit();
    thread->wait();
    qDebug() << "处理完数据后，关闭定时器!!!";
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_start->setEnabled(true);

}



